var TaskInfo = {
	grid: '#taskinfo-grid',
	form: '#taskinfoForm',

	init: function(){
		//初始化Grid列表数据
		this.initGrid();
	},

	//添加模块
	addTaskInfo: function(){
		var d = this.createTaskInfoDialog();
		d.dialog({title: "Add Job"}).dialog('open');
	},

	//修改模块弹出修改框
	updateTaskInfo: function() {
		var message = Ext.getSingleSelected(this.grid);
		if(message){
			return Ext.alert(message);
		}

		this.update();
	},

	//执行更新操作
	update: function() {
		var record = Ext.getRecord(TaskInfo.grid);
		var d = this.createTaskInfoDialog();
		d.dialog({title: "Edit Job"}).dialog('open');

		//加载form表单
		$(this.form).form('load', record);
		$('#taskinfoForm input[name=id]').val(1);
	},

	//删除模块
	deleteTaskInfo: function(){
		var message = Ext.getSingleSelected(this.grid);
		if(message){
			return Ext.alert(message);
		}

		Ext.confirm('您确认要删除这条记录吗?', function(){
			Ext.progress('Loading...');
			var record = Ext.getRecord(TaskInfo.grid);
			$.get("/delete/"+record.jobName+"/"+record.jobGroup, function(result){
				if(result.errorCode==0){
					$(TaskInfo.grid).datagrid("reload")
				}else{
					Ext.alert(result.errorText);
				}
				Ext.progressClose();
			});
		});
	},

	//模块详情
	detailTaskInfo: function(index){
		$(TaskInfo.grid).datagrid('selectRow',index);
		var row = Ext.getRecord(this.grid);
		if(!row){return;}

		//弹出Dialog, 并修改Title和隐藏Button
		var d = this.createTaskInfoDialog();
		d.dialog({title: "Detail Job"}).dialog('open');
		$(".dialog-button a").eq(0).hide();
		$(this.form).form('load', row)
	},

    //手动执行
    triggerNowTaskInfo: function(index) {
        $(TaskInfo.grid).datagrid('selectRow',index);
        var row = Ext.getRecord(this.grid);
        if(!row){return;}
        Ext.confirm('您确认要手动执行该任务吗?', function(){
            Ext.progress('正在手动执行任务...');
            var record = Ext.getRecord(TaskInfo.grid);
            $.ajax({
                    type  : 'post',
                    url :  "/triggerNow/"+record.jobGroup+"/"+record.jobName,
                    dataType :  'json',
                    data  : JSON.stringify({}),
                    //需要将当前的对象转换为json字符串,
                    contentType: 'application/json',
                    success  : function(result){
                        if(result.code==0){
                            $(TaskInfo.grid).datagrid("reload")
                        }else{
                            Ext.alert(result.msg);
                        }
                        Ext.progressClose();
                    },
                    error  : function(XMLHttpRequest, textStatus, errorThrown){}
                }
            );
        });
    },

	//暂停
	pauseTaskInfo: function(index) {
		$(TaskInfo.grid).datagrid('selectRow',index);
		var row = Ext.getRecord(this.grid);
		if(!row){return;}

		Ext.confirm('您确认要暂停该任务吗?', function(){
			Ext.progress('正在暂停任务...');
			var record = Ext.getRecord(TaskInfo.grid);
			$.post("/pause/"+record.jobGroup+"/"+record.jobName,function(result){
				if(result.code==0){
					$(TaskInfo.grid).datagrid("reload")
				}else{
					Ext.alert(result.msg);
				}
				Ext.progressClose();
			});
		});
	},

	//开始
	resumeTaskInfo: function(index) {
		$(TaskInfo.grid).datagrid('selectRow',index);
		var row = Ext.getRecord(this.grid);
		if(!row){return;}

		Ext.confirm('您确认要重新开始该任务吗?', function(){
			Ext.progress('正在重新开始任务...');
			var record = Ext.getRecord(TaskInfo.grid);
			$.post("/resume/"+record.jobGroup+"/"+record.jobName, function(result){
				if(result.code==0){
					$(TaskInfo.grid).datagrid("reload")
				}else{
					Ext.alert(result.msg);
				}
				Ext.progressClose();
			});
		});
	},
    removeTaskInfo: function(index) {
        $(TaskInfo.grid).datagrid('selectRow',index);
        var row = Ext.getRecord(this.grid);
        if(!row){return;}
        Ext.confirm('您确认要移除该任务吗?', function(){
            Ext.progress('正在移除任务...');
            var record = Ext.getRecord(TaskInfo.grid);
            $.post("/remove/"+record.jobGroup+"/"+record.jobName, function(result){
                if(result.code==0){
                    $(TaskInfo.grid).datagrid("reload")
                }else{
                    Ext.alert(result.msg);
                }
                Ext.progressClose();
            });
        });
    },
	//初始化表单
	initGrid: function(){
		$(this.grid).datagrid({
			toolbar: '#taskinfo-tbar',
		    url:'/queryALInitJobList?pageNum=1&pageSize=1',
		    method: 'post',
		    fitColumns: true,
		    striped: true,
		    fit: true,
		    pagination:false,
	        rownumbers:true,
	        ctrlSelect: false,
	        singleSelect: true,
	        border: false,
		    columns:[[
				{field:'id',title:'',checkbox:'true', width:20},
				{field:'jobName',title:'JobName',width:40,formatter:function(v,r,i){return '<a href="javascript:void(0)" onclick="TaskInfo.detailTaskInfo('+i+')">'+v+'</a>';}},
				{field:'jobGroup',title:'JobGroup',width:40},
				{field:'description',title:'description',width:50},
                {field:'runStatus',title:'runStatus',width:30,formatter:function(v,r,i){
                    var val = '';
                    if(r.jobStatus == 'NORMAL') {
                        val = '运行中'
                    }else if(r.jobStatus == 'PAUSED'){
                        val = '暂停'
                    }else{
                        val = r.jobStatus
                    }
                    return val;
                }
                },
				{field:'cronExpression',title:'CronExpression',width:40},
				{field:'runStartTime',title:'RunStartTime',width:60,formatter: formatDatebox},
                {field:'手动执行',title:'手动执行',width:120,formatter:function(v,r,i){
                    var val = '';
                    if(r.jobStatus == 'NORMAL') {
                        val += '<a href="javascript:void(0)"  onclick="TaskInfo.triggerNowTaskInfo('+i+')">执行一次</a>'
                        val += '<a href="javascript:void(0)" style="margin-left: 15px" onclick="TaskInfo.pauseTaskInfo('+i+')">暂停运行</a>'
                    }else if(r.jobStatus == 'PAUSED'){
                        val += '<a href="javascript:void(0)" onclick="TaskInfo.resumeTaskInfo('+i+')">开始运行</a>'
                    }
                    val += '<a href="javascript:void(0)" style="margin-left: 15px" onclick="TaskInfo.removeTaskInfo('+i+')">移除任务</a>'
                    return val;
                }
                }
		    ]]
		});
	},

	//模块框
	createTaskInfoDialog: function() {
		$(this.form).form('clear');
		$('#taskinfoForm input[name=id]').val(0);

		var d = $('#taskinfoDialog').dialog({
		    width:500,
		    minimizable: false,
		    maximizable: false,
		    collapsible: false,
		    resizable: false,
		    modal: true,
		    iconCls: 'icon-win',
		    buttons: [
		       {text: 'Save', handler: this.saveTaskInfo},
		       {text: 'Close', handler: function(){d.dialog('close');}}
		    ]
		});
		return d;
	}
}



Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
function formatDatebox(value) {
    if (value == null || value == '') {
        return '';
    }
    var dt;
    if (value instanceof Date) {
        dt = value;
    } else {
        dt = new Date(value);
    }

    return dt.format("yyyy-MM-dd hh:mm:ss.S"); //扩展的Date的format方法(上述插件实现)
}
